package com.rakuten.api.mule.transformers;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.RandomStringUtils;
import org.mule.api.MuleMessage;
import org.mule.api.transformer.TransformerException;
import org.mule.api.transport.PropertyScope;
import org.mule.transformer.AbstractMessageTransformer;

import com.rakuten.api.mule.model.FindShopInfo;
import com.rakuten.api.mule.model.Inventory;
import com.rakuten.api.mule.model.Product;
import com.rakuten.api.mule.model.Variants;
import com.rakuten.api.mule.model.inventory.InventoryBulkUpsertRequest;
import com.rakuten.api.mule.model.inventory.ItemUpsertReponse;
import com.rakuten.api.mule.model.inventory.Quantity;
import com.rakuten.api.mule.model.inventory.QuantityModifier;
import com.rakuten.api.mule.model.inventory.ShopInventoryBulkGetResponse.ShopInventory;
import com.rakuten.api.mule.model.item.Item;
import com.rakuten.api.mule.model.item.ItemPricing;
import com.rakuten.api.mule.model.item.ItemVariant;
import com.rakuten.api.mule.model.item.ItemVariant.ShopInfo;

public class CreateInventoryBulkUpsertRequest extends
		AbstractMessageTransformer {

	@Override
	public Object transformMessage(MuleMessage message, String outputEncoding)
			throws TransformerException {

		try {
			// Create a request object in which there are mutiple ItemVariantIds
			// per ShopID
			InventoryBulkUpsertRequest inventoryBulkUpsertRequest = new InventoryBulkUpsertRequest();
			// read shopInfoMap from message
			Map<String, FindShopInfo> findShopInfoMap = message.getProperty(
					"findShopInfoMap", PropertyScope.SESSION);
			// Item item = message.getProperty("itemInfo",
			// PropertyScope.SESSION);
			Product product = message.getProperty("productInfo",
					PropertyScope.SESSION);
			// Reponse of Api2, sku -> itemVariantIds
			ItemUpsertReponse itemUpsertReponse = message.getProperty(
					"itemUpsertReponse", PropertyScope.SESSION);
			
			// set merchant id
			String merchantId = message.getProperty("merchantId",
					PropertyScope.SESSION);			
			inventoryBulkUpsertRequest.setMerchantId(merchantId);
			// token , uniqule value
			SimpleDateFormat sdf1 = new SimpleDateFormat("yyMMddHHmmssZ");
			 String random1 = RandomStringUtils.randomNumeric(36);			
			 inventoryBulkUpsertRequest.setToken(random1);			 
			//inventoryBulkUpsertRequest.setToken("6bffafaa-7af9-4d1a-a268-6195ca3c1de9");

			// Read variants from product
			List<Variants> variantsList = product.getVariants();
			// itemVaiantIds, first string is shopurl, second is itemVariantID
			Map<String, Map<String, QuantityModifier>> ShopInventories = new HashMap<String, Map<String, QuantityModifier>>();

			// Vaiant単位でループ
			for (int counter1 = 0; counter1 < variantsList.size(); counter1++) {
				Variants variants = variantsList.get(counter1);
				// sku info
				String sku = variants.getSku();
				// get itemVariantId from sku - ItemVariantIds data
				String itemVariantId = itemUpsertReponse.getItemVariantIds()
						.get(sku);
				// read inventory list、Inventory単位でループ
				List<Inventory> inventoriesList = variants.getInventories();
				for (int counter2 = 0; counter2 < inventoriesList.size(); counter2++) {
					// Inventory情報
					QuantityModifier quantityModifier = new QuantityModifier();
					Inventory inventory = inventoriesList.get(counter2);
					// Request type
					quantityModifier.setRequestType("ADD");
					// recallable
					quantityModifier.setRecallable(true);
					// alertThreshold
					quantityModifier.setAlertThreshold(1);
					// Quantity
					Quantity quantity = new Quantity();
					quantity.setUnlimited(false);
					quantity.setValue(inventory.getQuantity());
					quantityModifier.setQuantity(quantity);
					// shopurl -> shopId
					FindShopInfo findShopInfo = findShopInfoMap.get(inventory
							.getShopURL());
					String shopId = findShopInfo.getShop().getShopId();
					
					// Check if Shop id exist
					// Shopは既存のデータに存在する場合、InventoryのMapへ情報を追加
					if (ShopInventories.get(shopId) != null) {
						Map<String, QuantityModifier> quantityModifierMap = ShopInventories
								.get(shopId);
						quantityModifierMap.put(itemVariantId, quantityModifier);
						ShopInventories.put(shopId, quantityModifierMap);
					} else {// Shopは既存のデータに存在しない場合、新規Inventory情報を作成
						Map<String, QuantityModifier> quantityModifierMap = new HashMap<String, QuantityModifier>();
						quantityModifierMap.put(itemVariantId, quantityModifier);
						ShopInventories.put(shopId, quantityModifierMap);						
					}
				}
				inventoryBulkUpsertRequest.setShopInventories(ShopInventories);
			}
			// Save ojbect to Payload
			message.setPayload(inventoryBulkUpsertRequest);

		} catch (Exception e) {
			throw new TransformerException(this, e);
		}
		
		return message;

	}
}
